#pragma once
#include "nocopy.hpp"
#include "Comm.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"

#include <iostream>
#include <cstdint>
#include <cstring>
#include <cerrno>
#include <stdlib.h>
#include <functional>
#include <unistd.h>
#include <unordered_map>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <signal.h>

#define CONV(addr_ptr) ((struct sockaddr *)(addr_ptr))
using task_t = std::function<void()>;
using callback_t = std::function<void(int, const InetAddr&)>;

class TcpServer : public nocopy
{
public:
    TcpServer(int port)
        : _port(port), _isinit(false)
    {
    }
    void Init()
    {
        // 1.创建套接字
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            lg.LogMessage(Fatal, "lietensock create error, errno: %d, %s\n", errno, strerror(errno));
            exit(listensockfd_err);
        }
        lg.LogMessage(Debug, "lietensock create success, listensock: %d\n", _listensock);

        // 解决重复bind失败的问题
        int opt = 1;
        setsockopt(_listensock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof opt);

        // 2.bind
        struct sockaddr_in server;
        memset(&server, 0, sizeof server);
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = INADDR_ANY;
        server.sin_port = htons(_port);
        int ok = bind(_listensock, CONV(&server), sizeof server);
        if (ok == -1)
        {
            lg.LogMessage(Fatal, "bind error, errno: %d, %s\n", errno, strerror(errno));
            exit(bind_err);
        }
        lg.LogMessage(Debug, "bind success\n");

        // 3.设置fd为监听状态
        ok = listen(_listensock, 5);
        if (ok == -1)
        {
            lg.LogMessage(Fatal, "listem error, errno: %d, %s\n", errno, strerror(errno));
            exit(listen_err);
        }
        lg.LogMessage(Debug, "listen success\n");

        _isinit = true;
        
        ThreadPool<task_t>::GetInstance()->Start();
    }
    void Service(int sockfd)
    {
        while (true)
        {
            char buffer[1024];
            int n = read(sockfd, buffer, sizeof buffer - 1);
            std::cout << "n:" << n << std::endl;
            if (n > 0)
            {
                buffer[n] = 0;
                // write(sockfd, buffer, sizeof buffer); //
                write(sockfd, buffer, strlen(buffer));

                // std::string str = buffer;
                // write(sockfd, str.c_str(), str.size());
            }
            else if (n == 0)
            {
                lg.LogMessage(Info, "client 断开连接或者读完\n");
                break;
            }
            else
            {
                lg.LogMessage(Error, "读错误, errno:%d, %s\n", errno, strerror(errno));
                break;
            }
        }
    }
    void Service(int sockfd, const std::string& addr)
    {
        while (true)
        {
            char buffer[1024];
            int n = read(sockfd, buffer, sizeof buffer - 1);
            std::cout << "n:" << n << std::endl;
            if (n > 0)
            {
                buffer[n] = 0;
                // write(sockfd, buffer, sizeof buffer); //
                // write(sockfd, buffer, strlen(buffer));

                std::string str = addr;
                std::cout << "TSVR " << addr << addr.size()<< std::endl; //Debug
                str += buffer;
                std::cout << "str " << str << str.size()<< std::endl; //Debug

                write(sockfd, str.c_str(), str.size());
            }
            else if (n == 0)
            {
                lg.LogMessage(Info, "client 断开连接或者读完\n");
                break;
            }
            else
            {
                lg.LogMessage(Error, "读错误, errno:%d, %s\n", errno, strerror(errno));
                break;
            }
        }
    }

    void Start()
    {
        while (_isinit)
        {
            struct sockaddr_in client;
            socklen_t len = 0;
            int sockfd = accept(_listensock, CONV(&client), &len); // 这里失败是很正常
            std::cout << "sockfd: " << sockfd << std::endl;
            if (sockfd < 0)
            {
                lg.LogMessage(Warning, "acceept falied, errno: %d, %s\n", errno, strerror(errno));
                continue; // 三次握手失败，
            }
            lg.LogMessage(Debug, "acceept success\n");

            InetAddr addr(client);
            std::cout << inet_ntoa(client.sin_addr) << std::endl; //Debug  这个没问题
            std::cout << addr.PrintDebug() << std::endl;            //Debug 这里不对
            task_t task = std::bind(&TcpServer::Route, this, sockfd, addr);
            ThreadPool<task_t>::GetInstance()->Push(task);
        }
    }
    std::string Read(int sockfd)
    {
        char buffer[64];
        std::cout << "readsockfd: " << sockfd << std::endl; // Debug
        int ok = read(sockfd, buffer, sizeof buffer);
        buffer[ok] = 0;             //难怪一连上就断开，这样子下面匹配不进去
        std::cout << "ok: " << ok << std::endl;
        if(ok > 0)
            return buffer;
        else if(ok == 0)
            lg.LogMessage(Warning, "client closed\n");
        else 
            lg.LogMessage(Error, "读错误, errno:%d, %s\n", errno, strerror(errno));
        return "default";
    }
    void Route(int sockfd, const InetAddr& addr)
    {
        std::string str = Read(sockfd); 
        std::cout << "read: " << str << str.size()<< std::endl;;  //Debug
        if(str == "ping")
            _funcs[str](sockfd, addr);
        else if(str == "translate")
            _funcs[str](sockfd, addr);
        else if(str == "transform")
            _funcs[str](sockfd, addr);
        else
            _funcs["default"](sockfd, addr);
        close(sockfd);
    }
    void Register(const std::string& str, callback_t cb)
    {
        _funcs[str] = cb;
    }
    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    int _listensock;
    bool _isinit;

    std::unordered_map<std::string, callback_t> _funcs;
};

//3.10有疑问，我觉得不用注释掉1